package com.excesys.exsecs.scada.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.excesys.exsecs.access.constant.RedisConstant;
import com.excesys.exsecs.access.entity.AccessDeviceInfo;
import com.excesys.exsecs.access.entity.AccessThingModel;
import com.excesys.exsecs.access.mapper.AccessDeviceInfoMapper;
import com.excesys.exsecs.access.mapper.AccessThingModelMapper;
import com.excesys.exsecs.scada.service.DeviceModelService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class DeviceModelServiceImpl implements DeviceModelService {

	private final AccessDeviceInfoMapper deviceInfoMapper;
	private final AccessThingModelMapper thingModelMapper;
	private final StringRedisTemplate redisTemplate;
	@Override
	public JSONObject getThing(String unitNo) {
		AccessDeviceInfo accessDeviceInfo = deviceInfoMapper.selectOne(Wrappers.<AccessDeviceInfo>lambdaQuery()
				.eq(AccessDeviceInfo::getUnitNo, unitNo));
		AccessThingModel accessThingModel = thingModelMapper.selectOne(Wrappers.<AccessThingModel>lambdaQuery()
				.eq(AccessThingModel::getProductKey, accessDeviceInfo.getProductKey()));
		JSONObject model = accessThingModel.getModel();
		model.set("deviceName",accessDeviceInfo.getDeviceName());
		model.set("remark", StringUtils.isEmpty(accessDeviceInfo.getRemark())?"---":accessDeviceInfo.getRemark());
		//获取属性
		List<JSONObject> properties =(List<JSONObject>) model.get("properties");
		//获取通道实时数据
		Object object = redisTemplate.opsForHash().get(RedisConstant.REPORT_LIST_KEY, unitNo);
		if(ObjectUtil.isNotNull(object)){
			JSONObject redisObject = new JSONObject(object.toString());
			Map map = (Map) redisObject.get("data");
			Set<Map.Entry<String, BigDecimal>> entries = map.entrySet();
			Map temap = new HashMap<>();
			for(Map.Entry<String, BigDecimal> entry : entries){
				temap.put(entry.getKey(),entry.getValue());
			}
			//System.out.println(temap);
			for (int i = 0; i < properties.size(); i++) {
				String channel = properties.get(i).getStr("identifier");
				properties.get(i).set("value", temap.get(channel));
			}
			model.set("properties", properties);
			return model;
		}
		return null;
	}

	/**
	 * 根据
	 * @param unitNo
	 * @return
	 */
	@Override
	public List getSceneInfo(String unitNo) {

		return null;
	}


}
